package com.jwdf.uda.ui.fragment.search;

import android.os.Bundle;

import com.jwdf.uda.R;
import com.jwdf.uda.bean.PbBean;
import com.jwdf.uda.event.MessageNoticeEvent;
import com.jwdf.uda.http.AHttpService;
import com.jwdf.uda.http.HttpHelper;
import com.jwdf.uda.http.action.SearchAction;
import com.jwdf.uda.http.action.UserAddFollowAction;
import com.jwdf.uda.http.action.UserCancelFollowAction;
import com.jwdf.uda.ui.activity.UserInfoActivity;
import com.jwdf.uda.ui.adapter.UserSimpleAdapter;
import com.jwdf.uda.ui.adapter.item.UserSimpleItem;
import com.jwdf.uda.ui.fragment.base.SimpleListFragment;
import com.jwdf.uda.utils.EventBusUtil;

import retrofit2.Response;

/**
 * Created by Administrator on 2016/5/20.
 */
public class SearchUserFragment extends SimpleListFragment {
    private String mContent;

    private UserSimpleAdapter mAdapter;

    public static SearchUserFragment instance(String content) {
        SearchUserFragment view = new SearchUserFragment();
        Bundle args = new Bundle();
        args.putString("content", content);
        view.setArguments(args);
        return view;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContent = getArguments().getString("content", "");
    }

    @Override
    protected boolean canPullRefresh() {
        return true;
    }

    @Override
    protected void initViews() {
        mAdapter = new UserSimpleAdapter(getContext());
        mAdapter.setCurrentUser(true);
        mAdapter.setOnUserFollowTypeListener(createUserFollowTypeListener());
        mDataBinding.commonFragmentList.setPullEnable(true);
        mDataBinding.commonFragmentList.setAdapter(mAdapter);
    }

    @Override
    protected void onListItemClick(int position) {
        if (position < 0) return;
        PbBean.PbUserSimple user = mAdapter.getItem(position).userSimple;
        UserInfoActivity.start(getContext(), user.getUserId(), user.getIsDesigner());
    }

    @Override
    protected void requestData(final boolean refresh) {
        if (refresh && mAdapter.isEmpty()) {
            showProgressDialog();
        }
        int offset = refresh ? 0 : mAdapter.getCount();
        onNewRequestCall(SearchAction.newInstance(getContext(), mContent, offset, PbBean.PbSignSearchType.SEARCH_TYPE_USER)
                .request(new AHttpService.IResCallback<PbBean.PbResPageSearch>() {
                    @Override
                    public void onCallback(int resultCode, Response<PbBean.PbResPageSearch> response, PbBean.PbBaseServerInfo
                            baseServerInfo) {
                        if (getView() != null) {
                            closeProgressDialog();
                            if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                                mDataBinding.commonFragmentList.stopRefresh();
                                mDataBinding.commonFragmentList.stopLoadMore();
                                return;
                            }
                            doSuccessResponse(refresh, response.body());
                        }
                    }
                }));
    }

    private UserSimpleAdapter.OnUserFollowTypeListener createUserFollowTypeListener() {
        return new UserSimpleAdapter.OnUserFollowTypeListener() {
            @Override
            public void onAddFollow(String userId) {
                addFollow(userId);
            }

            @Override
            public void onCancelFollow(String userId) {
                cancelFollow(userId);
            }
        };
    }

    private void refreshUserInfo() {
        requestData(true);
        EventBusUtil.post(new MessageNoticeEvent(MessageNoticeEvent.REFRESH_USER_INFO));
    }

    private void addFollow(String userId) {
//        showProgressDialog();
        onNewRequestCall(UserAddFollowAction.newInstance(getContext(), userId).request(new AHttpService.IResCallback<PbBean.PbResUserAddFollow>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserAddFollow> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (getView() != null) {
//                    closeProgressDialog();
                    if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                        return;
                    }
                    refreshUserInfo();
                }
            }
        }));
    }

    private void cancelFollow(String userId) {
//        showProgressDialog();
        onNewRequestCall(UserCancelFollowAction.newInstance(getContext(), userId).request(new AHttpService.IResCallback<PbBean.PbResUserDelFollow>() {
            @Override
            public void onCallback(int resultCode, Response<PbBean.PbResUserDelFollow> response, PbBean.PbBaseServerInfo baseServerInfo) {
                if (getView() != null) {
//                    closeProgressDialog();
                    if (HttpHelper.showError(getContext(), resultCode, baseServerInfo, getString(R.string.error_net))) {
                        return;
                    }
                    refreshUserInfo();
                }
            }
        }));
    }

    private void doSuccessResponse(boolean refresh, PbBean.PbResPageSearch body) {
        if (body != null) {
            if (body.getUserListList().isEmpty()) {
                mDataBinding.tvEmptyData.setText("对不起，未找到符合条件的用户");
                mDataBinding.commonFragmentList.setEmptyView(mDataBinding.tvEmptyData);
            } else {
                if (refresh) {
                    mAdapter.setData(UserSimpleItem.convert(body.getUserListList()));
                } else {
                    mAdapter.append(UserSimpleItem.convert(body.getUserListList()));
                }
            }
            mDataBinding.commonFragmentList.setPullLoadEnable(body.getUserListList().size() == getPageLength());
            mDataBinding.commonFragmentList.stopRefresh();
            mDataBinding.commonFragmentList.stopLoadMore();
        }
    }
}
